package com.zhima.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.zhima.constant.RedisConstant;
import com.zhima.properties.OjMailProperties;
import com.zhima.service.CheckCodeService;
import com.zhima.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import static com.zhima.constant.RedisConstant.*;

@Service
public class EmailCheckCodeServiceImpl implements CheckCodeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private EmailService emailService;
    @Autowired
    private OjMailProperties ojMailProperties;

    @Override
    public String sendCheckCode(String address) {
        String checkCode = RandomUtil.randomNumbers(6);
        // 发邮件
        emailService.send(address, buildCheckCodeContent(checkCode));
        // 设置有效期
        stringRedisTemplate.opsForValue().set(RedisConstant.emailCheckCodeKey(address), checkCode, CHECK_CODE_EXPIRE_TIME, CHECK_CODE_EXPIRE_TIME_UNIT);
        return checkCode;
    }

    private String buildCheckCodeContent(String checkCode) {
        return String.format(
                "%s%s%s",
                ojMailProperties.getCheckCodePrefix(),
                checkCode,
                ojMailProperties.getCheckCodeSuffix()
        );
    }

    @Override
    public String getCheckCode(String address) {
        return stringRedisTemplate.opsForValue().get(emailCheckCodeKey(address));
    }
}
